import 'dart:async';
import 'package:flutter/material.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/common.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/models/SearchModel.dart';
import 'package:qgchat/states/states_model/index.dart';

class SearchBloc implements BlocBase {

  void init() {
    getHistory();
    getFateforList();
  }

  void dispose(){
    _already.close();
    _textField.close();
    _search.close();
    _fatefor.close();
    _history.close();
  }

  // // 列表控制器
  // final ScrollController _custom = ScrollController();
  // // 当前搜索的文字
  // String searchText;
  /// 搜索控制器
  TextEditingController searchC = TextEditingController();

  // ##########  DEFAULT  ##############

  // 是否已经搜索过一次状态
  bool alreadySearchStatus = false;

  // 正在搜索状态
  bool onSearchStatus = false;

  // ##########  STREAMS  ##############
  // 注：搜索模型、与你有缘用、搜索历史 用了同一个模型，若他日数据格式不同，请区分开两个模型

  /// 搜索状态stream
  StreamController<bool> _already = StreamController.broadcast();
  Sink<bool> get _inAlreadySink => _already.sink;
  Stream<bool> get outAlreadyStream => _already.stream;

  /// 搜索状态stream
  StreamController<bool> _textField = StreamController.broadcast();
  Sink<bool> get _inTextFieldSink => _textField.sink;
  Stream<bool> get outTextFieldStream => _textField.stream;

  /// 搜索stream
  StreamController<List<SearchModel>> _search = StreamController.broadcast();
  Sink<List<SearchModel>> get _inSearchSink => _search.sink;
  Stream<List<SearchModel>> get outSearchStream => _search.stream;

  /// 与你有缘stream
  StreamController<List<SearchModel>> _fatefor = StreamController.broadcast();
  Sink<List<SearchModel>> get _inFateforSink => _fatefor.sink;
  Stream<List<SearchModel>> get outFateforStream => _fatefor.stream;

  /// 历史记录stream
  StreamController<List<String>> _history = StreamController.broadcast();
  Sink<List<String>> get _inHistorySink => _history.sink;
  Stream<List<String>> get outHistoryStream => _history.stream;

  // ##########  HANDLING  ##############

  /// 与你有缘
  List<SearchModel> youyuan = [];
  /// 搜索出列表
  List<SearchModel> sousuo = [];

  /// 搜索列表数据
  void onSubmitted(String key) async {
    _inAlreadySink.add(true);
    _inTextFieldSink.add(true);

    setHistory(key);

    List<SearchModel> result = await CommonApis.search(key);
    _inSearchSink.add(result);
    _inTextFieldSink.add(false);

    sousuo = result;

    searchC.text = key;
    searchC.selection = TextSelection.collapsed(offset: key.runes.length);
  }

  /// 与你有缘列表数据
  void getFateforList() async {
    List<SearchModel> result = await CommonApis.fatefor();
    if (!_fatefor.isClosed) {
      youyuan = result;
      _inFateforSink.add(result);
    }
  }

  /// 主播历史搜索记录
  void getHistory() {
    String json = cache.getString('anchorHistory');
    if (json == null) {
      return;
    }
    List<String> history = [];
    List list = deJson(json);
    list.forEach((item) {
      history.add(item);
    });
    if (history.length > 10) {
      history.removeRange(3, history.length);
    }
    Timer(Duration(seconds: 1), () {
      _inHistorySink.add(history);
    });
  }

  /// 存储历史搜索记录
  void setHistory(String key) {
    String json = cache.getString('anchorHistory');
    List<String> history = List<String>();
    if (json != null) {
      List list = deJson(json);
      list.forEach((item) {
        history.add(item);
      });
    }
    if (!history.contains(key)) {
      history.insert(0, key);
      if (history.length > 10) {
        history.removeRange(10, history.length);
      }
      cache.setString('anchorHistory', toJson(history));
    }
  }

  /// 关注主播
  void follow(int id) async {
    Map result = await UserApis.follow(id);
    if (result['status'] == 1) {
      int i = youyuan.indexWhere((item) => item.id == id);
      if (i != -1) {
        _inFateforSink.add(youyuan);
        youyuan[i].follow = 1;
      }
      int si = sousuo.indexWhere((item) => item.id == id);
      if (si != -1) {
        _inSearchSink.add(sousuo);
        sousuo[si].follow = 1;
      }
      UserState userState = state(Global.context, 'user');
      userState.userInfo();
      showToast("关注成功");
    }
  }
  
  /// 取消关注
  void cancelfollow(int id, String name) async {
    Map result = await UserApis.cancelfollow(id);
    if (result['status'] == 1) {
      int i = youyuan.indexWhere((item) => item.id == id);
      if (i != -1) {
        _inFateforSink.add(youyuan);
        youyuan[i].follow = 0;
      }
      int si = sousuo.indexWhere((item) => item.id == id);
      if (si != -1) {
        _inSearchSink.add(sousuo);
        sousuo[si].follow = 0;
      }
      UserState userState = state(Global.context, 'user');
      userState.userInfo();
      showToast("取消关注$name");
    }
  }
}